module.exports = {
    dbName: 'fire', // 数据库名称
    dbPath: '_doc/fire.db', // 数据库地址，推荐以下划线为开头   _doc/xxx.db

    async isOpen() {
        return plus.sqlite.isOpenDatabase({
            name: this.dbName,
            path: this.dbPath
        });
    },

    async openSqlite() {
        await plus.sqlite.openDatabase({
            name: this.dbName,
            path: this.dbPath
        });
    },

    async closeSqlite() {
        await plus.sqlite.closeDatabase({
            name: this.dbName
        });
    },

    async createTable(dbTable, data) {
        const sql = `CREATE TABLE IF NOT EXISTS ${dbTable}(${data})`;
        await this.executeSql(sql, `Error creating table in ${dbTable}`);
    },

    async dropTable(dbTable) {
        const sql = `DROP TABLE IF EXISTS ${dbTable}`;
        await this.executeSql(sql, `Error dropping table ${dbTable}`);
    },

    async insertTableData(dbTable, data, condition) {
        if (!dbTable || !data) {
            throw new Error("Invalid parameters for insertTableData");
        }

        const values = condition ? `(${condition})` : '';
        const sql = `INSERT INTO ${dbTable} ${values} VALUES(${data})`;
        console.log(sql);
        await this.executeSql(sql, `Error inserting data into ${dbTable}`);
    },

    async insertOrReplaceData(dbTable, data, condition) {
        if (!dbTable || !data) {
            throw new Error("Invalid parameters for insertOrReplaceData");
        }

        const columns = condition ? `(${condition})` : '';
        const values = Array.isArray(data) ? data.join(',') : data;
        const sql = `INSERT OR REPLACE INTO ${dbTable} ${columns} VALUES(${values})`;

        await this.executeSql(sql, `Error inserting or replacing data in ${dbTable}`);
    },

    async selectTableData(dbTable, conditions) {
        if (!dbTable) {
            throw new Error("Invalid parameters for selectTableData");
        }

        let sql = `SELECT * FROM ${dbTable}`;
        if (conditions) {
            sql += ` WHERE ${conditions.join(' AND ')}`;
        }

        return await this.selectSql(sql, `Error selecting data from ${dbTable}`);
    },

    async deleteTableData(dbTable, lname, lvalue, ww, ee) {
        if (!dbTable) {
            throw new Error("Invalid parameters for deleteTableData");
        }

        let sql = `DELETE FROM ${dbTable}`;
        if (lname) {
            if (ww) {
                sql += ` WHERE ${lname} = '${lvalue}' AND ${ww} = '${ee}'`;
            } else {
                sql += ` WHERE ${lname} = '${lvalue}'`;
            }
        }

        await this.executeSql(sql, `Error deleting data from ${dbTable}`);
    },

    async updateTableData(dbTable, data, lname, lvalue) {
        if (!dbTable || !data) {
            throw new Error("Invalid parameters for updateTableData");
        }

        const updateClause = lname ? `SET ${data} WHERE ${lname} = '${lvalue}'` : `SET ${data}`;
        const sql = `UPDATE ${dbTable} ${updateClause}`;

        await this.executeSql(sql, `Error updating data in ${dbTable}`);
    },

    async pullSQL(dbTable, id, num) {
        const sql = `SELECT * FROM ${dbTable} ORDER BY ${id} DESC LIMIT 15 OFFSET ${num}`;
        return await this.selectSql(sql, `Error pulling data from ${dbTable}`);
    },

    async executeSql(sql, errorMessage) {
        try {
            await new Promise((resolve, reject) => {
                plus.sqlite.executeSql({
                    name: this.dbName,
                    sql: sql,
                    success: resolve,
                    fail: (e) => {
                        console.log('fail', e);
                    }
                });
            });
        } catch (error) {
            throw new Error(`${errorMessage}: ${error.message}`);
        }
    },

    async selectSql(sql, errorMessage) {
        try {
            return await new Promise((resolve, reject) => {
                plus.sqlite.selectSql({
                    name: this.dbName,
                    sql: sql,
                    success: resolve,
                    fail: reject
                });
            });
        } catch (error) {
            throw new Error(`${errorMessage}: ${error.message}`);
        }
    }
}
